iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0
Software Development

我們與Maven的距離系列 第 18

Day17 - BOM (Bill of Materials)

  • 分享至 

  • xImage
  •  

前言

在前面的章節中,我們學習了 Maven 的繼承和聚合機制。但隨著專案規模的擴大,您可能會遇到一個棘手的問題:當您需要管理大量相關套件的版本時,單一繼承的限制就會顯現出來。今天我們來學習 Maven 的 BOM 機制,如何來解決這樣的問題?

什麼是BOM (Bill of Materials)

問題背景:單一繼承的限制

Maven 的 POM 繼承就像 Java 類別一樣,只支援單一繼承

實際遇到的問題
假設您的專案需要使用以下套件組合:

  1. Spring Boot 生態系:相關套件版本非常多,例如:Spring Boot Dependencies
  2. Apache Commons 系列:需要管理多個工具套件版本

困難點

  • 無法同時繼承 Spring Boot Parent 和 Apache Commons Parent
  • 手動管理幾十個套件版本容易出錯
  • 版本不一致可能導致相容性問題

BOM 的解決方案
BOM (Bill of Materials) 是一種特殊的 POM 文件,它的作用是:

  • 統一定義一組相關套件的版本清單
  • 透過 import scope 讓其他專案引用這些版本定義
  • 不是繼承關係,透過<dependencyManagement>設置

範例演示

我們參考我們day15的專案,並引入Spring Boot Dependencies來統一我們的版本控管,詳細Spring Boot統一版本設置請點我
父層pom.xml設定,<dependency>type要設為pom,dependency scope要設為import

<project>
  <groupId>com.mycompany</groupId>
  <artifactId>myApp</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>myApp</name>
  <packaging>pom</packaging>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>21</maven.compiler.source>
    <maven.compiler.target>21</maven.compiler.target>
  </properties>

  <dependencyManagement>
    <dependencies>
        <!-- 匯入 Spring Boot BOM -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>3.5.6</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
  </dependencyManagement>
  <dependencies>
    <!-- 這些就不用再寫版本號了,因為 BOM 幫你統一管理 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>
  <modules>
    <module>core</module>
    <module>service</module>
    <module>infrastructure</module>
    <module>web</module>
  </modules>
</project>

小結

今天我們學習了 Maven BOM (Bill of Materials) 機制,透過<scope>import</scope>來統一管理大量相關套件版本

Reference


上一篇
Day16 - Project Aggregation
下一篇
Day18 - Profile
系列文
我們與Maven的距離24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言